package com.xsy.localgame.puzzle;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.xsy.localgame.R;

import java.util.Collections;
import java.util.List;

public class GamePintuLayout extends RelativeLayout implements View.OnClickListener {

    /**
     * 设置Item的数量n*n；默认为3
     */
    private int mColumn = 3;
    /**
     * 布局的宽度
     */
    private int mWidth;
    /**
     * 布局的padding
     */
    private int mPadding;
    /**
     * 存放所有的Item
     */
    private ImageView[] mGamePintuItems;
    /**
     * Item的宽度
     */
    private int mItemWidth;
    /**
     * Item横向与纵向的边距
     */
    private int mMargin = 3;
    /**
     * 拼图的图片
     */
    private Bitmap mBitmap;
    /**
     * 存放切完以后的图片bean
     */
    private List<ImagePiece> mItemBitmaps;

    /**
     * 初始化界面的标记
     */
    private boolean once;

    private ChangeLevelListener levelListener;

    public void setLevelListener(ChangeLevelListener levelListener) {
        this.levelListener = levelListener;
    }

    public GamePintuLayout(Context context) {
        this(context,null);
    }

    public GamePintuLayout(Context context, AttributeSet attrs) {
        this(context, attrs,0);
    }

    public GamePintuLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //把设置的margin值转换为dp
        mMargin = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,mMargin,
                getResources().getDisplayMetrics());
        // 设置Layout的内边距，四边一致，设置为四内边距中的最小值
        mPadding = min(getPaddingLeft(), getPaddingTop(), getPaddingRight(),
                getPaddingBottom());
    }

    /**
     * 自定义view宽高
     */
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        mWidth = Math.min(getMeasuredHeight(),getMeasuredWidth());
        if (!once) {
            initBitMap();
            initItem();
        }

        once = true;
        setMeasuredDimension(mWidth,mWidth);
    }

    /**
     * 初始化图片
     */
    private void initBitMap() {
        if (mBitmap == null) {
            mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.image_default);
        }

        mItemBitmaps = ImageSplitter.split(mBitmap,mColumn);
        //对图片进行排序
        Collections.sort(mItemBitmaps, (imagePiece, t1) -> {
            //随机比较大小
            return Math.random() >  0.5 ? 1 : -1;
        });
    }

    /**
     * 初始化每个item
     */
    private void initItem() {
        //获得item宽度
        int childWidth = (mWidth - mPadding * 2 - mMargin * (mColumn + 1)) / mColumn;
        mItemWidth = childWidth;

        mGamePintuItems = new ImageView[mColumn * mColumn];
        //放置item
        for (int i = 0; i < mGamePintuItems.length; i++) {
            ImageView item = new ImageView(getContext());
            item.setOnClickListener(this);

            item.setImageBitmap(mItemBitmaps.get(i).bitmap);
            mGamePintuItems[i] = item;
            item.setId(i + 1);
            item.setTag(i + "_" + mItemBitmaps.get(i).index);

            LayoutParams layoutParams = new LayoutParams(mItemWidth,mItemWidth);
            //设置横向编辑，不是最后一列
            if ((i + 1) % mColumn != 0) {
                layoutParams.rightMargin = mMargin;
            }

            //如果不是第一列
            if (i % mColumn != 0) {
                layoutParams.addRule(RelativeLayout.RIGHT_OF,mGamePintuItems[i - 1].getId());
            }

            //如果不是第一行 ，设置纵向编剧，不是最后一行
            if ((i + 1) > mColumn) {
                layoutParams.topMargin = mMargin;
                layoutParams.addRule(RelativeLayout.BELOW,mGamePintuItems[i - mColumn].getId());
            }
            addView(item,layoutParams);
        }
    }

    /**
     *  用来得到最小值
     */
    private int min(int...params) {
        int minValue = params[0];
        for (int param :params) {
            if (minValue > param) {
                minValue = param;
            }
        }
        return minValue;
    }

    /**
     * 记录第一次点击的ImageView
     */
    private ImageView mFirst;
    /**
     * 记录第二次点击的ImageView
     */
    private ImageView mSecond;

    @Override
    public void onClick(View view) {
        if (isAniming) {
            return;
        }

        //如果两次单机的是同一个View
        if (mFirst == view) {
            mFirst.setColorFilter(null);
            mFirst = null;
            return;
        }

        //点击第一个View
        if (mFirst == null) {
            mFirst = (ImageView) view;
            mFirst.setColorFilter(Color.parseColor("#55FF0000"));
        } else {//点击第二个view
            mSecond = (ImageView) view;
            exChangeView();
        }
    }

    /**
     * 动画运行的标志位
     */
    private boolean isAniming;
    /**
     * 动画层
     */
    private RelativeLayout mAnimLayout;

    /**
     * 交换两个图片之间的位置
     */
    private void exChangeView() {
        mFirst.setColorFilter(null);
        setUpAnimLayout();
        //添加firstView
        ImageView first = new ImageView(getContext());
        first.setImageBitmap(mItemBitmaps.get(getImageIndexByTag((String) mFirst.getTag())).bitmap);
        LayoutParams lp = new LayoutParams(mItemWidth,mItemWidth);
        lp.leftMargin = mFirst.getLeft() - mPadding;
        lp.topMargin = mFirst.getTop() - mPadding;
        first.setLayoutParams(lp);
        mAnimLayout.addView(first);

        //添加secondView
        ImageView second = new ImageView(getContext());
        second.setImageBitmap(mItemBitmaps.get(getImageIndexByTag((String) mSecond.getTag())).bitmap);
        LayoutParams lp2 = new LayoutParams(mItemWidth,mItemWidth);
        lp2.leftMargin = mSecond.getLeft() - mPadding;
        lp2.topMargin = mSecond.getTop() - mPadding;
        second.setLayoutParams(lp2);
        mAnimLayout.addView(second);

        //设置动画
        TranslateAnimation anim = new TranslateAnimation(0,
                mSecond.getLeft() -  mFirst.getLeft(),0,
                mSecond.getTop() - mFirst.getTop());
        anim.setDuration(300);
        anim.setFillAfter(true);
        first.startAnimation(anim);

        TranslateAnimation animSecond = new TranslateAnimation(0,mFirst.getLeft() - mSecond.getLeft()
                ,0,mFirst.getTop() - mSecond.getTop());
        animSecond.setDuration(300);
        animSecond.setFillAfter(true);
        second.startAnimation(animSecond);

        //监听动画
        anim.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                isAniming = true;
                mFirst.setVisibility(INVISIBLE);
                mSecond.setVisibility(INVISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                String firstTag = (String) mFirst.getTag();
                String secondTag = (String) mSecond.getTag();

                String[] firstParams = firstTag.split("_");
                String[] secondParams = secondTag.split("_");

                mFirst.setImageBitmap(mItemBitmaps.get(Integer.parseInt(secondParams[0])).bitmap);
                mSecond.setImageBitmap(mItemBitmaps.get(Integer.parseInt(firstParams[0])).bitmap);

                mFirst.setTag(secondTag);
                mSecond.setTag(firstTag);
                mFirst.setVisibility(VISIBLE);
                mSecond.setVisibility(VISIBLE);

                mFirst = mSecond = null;
                mAnimLayout.removeAllViews();
                isAniming = false;
                //判断游戏是否胜利
                checkSuccess();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    /**
     * 判断游戏是否成功
     */
    private void checkSuccess() {
        boolean isSuccess = true;
        for (int i = 0; i < mGamePintuItems.length; i++) {
            ImageView first = mGamePintuItems[i];
            if (getIndexByTag((String) first.getTag()) != i) {
                isSuccess = false;
            }
        }

        if (isSuccess) {
            Toast.makeText(getContext(), "next level", Toast.LENGTH_SHORT).show();
            nextLevel();
        }
    }

    /**
     * 进入下一关
     */
    private void nextLevel() {
        this.removeAllViews();
        mAnimLayout = null;
        mColumn++;
        initBitMap();
        initItem();
        if (levelListener != null) {
            levelListener.onSuccess(mColumn);
        }
    }

    /**
     * 手动设置难度等级
     */
    public void setLevel(int levels) {
        if (levels < 3) {
            return;
        }
        this.removeAllViews();
        mAnimLayout = null;
        mColumn = levels;
        initBitMap();
        initItem();
    }

    /**
     * 获得存储在mItemBitmaps中存储图片的角标
     */
    private int getImageIndexByTag(String tag) {
        String[] split = tag.split("_");
        return Integer.parseInt(split[0]);
    }

    /**
     * 创建动画层
     */
    private void setUpAnimLayout() {
        if (mAnimLayout == null) {
            mAnimLayout = new RelativeLayout(getContext());
            addView(mAnimLayout);
        }
    }

    /**
     * 获得图片的真正索引
     */
    private int getIndexByTag(String tag) {
        String[] split = tag.split("_");
        return Integer.parseInt(split[1]);
    }

    public void setBitMap(Bitmap bitmap) {
        this.mBitmap = bitmap;
        this.removeAllViews();
        mAnimLayout = null;
        initBitMap();
        initItem();
    }
}
